<script>
  import render from "@/components/render/render.js";
  import VueGridLayout from "vue-grid-layout";
  import loginPage from "../mobileComponents/loginForm.vue";
  import { getRouters } from "@/api/menu";
  import searchCent from '../mobileComponents/searchCent.vue'
  function freeDraw(h,freeobj){
    return   <van-tabs type={freeobj.styletype===1?'line':'card'} ref={'free'+freeobj.__config__.renderKey} onClick={(n)=>{this.setTabRefresh()}}>
           {
            freeobj.tabList.map((item,mid)=>{
          return (
           
            <van-tab key={mid} title={item.title}>
            {this.showbiao? <grid-layout
                    layout={item.fields}
                    col-num={12}
                      row-height={30}
                      is-resizable={false}
                      is-mirrored={false}
                      vertical-compact={false}
                      key={''+freeobj.i+mid}
                      is-draggable={false}
                      auto-size={false}
                      margin={[0,5]}
                      use-css-transforms={false}
                      use-style-cursor={false}
                  
                  >
               {
                item.fields.map((val,ind)=>{
                  return <grid-item 
                      x={val.x}
                      y={val.y}
                      w={val.w}
                      h={val.h}
                      i={val.i}
                      key={val.i}
                      style={{
                              background: "white"
                            }}
                     >
                     <div
                              style={{width: '100%',background:'white',height:'100%',overflow:'hidden'}}
                              onClick={() => {
                                this.changepath((val.jumpType==='page'?val.jumpPath:val.functionMenu), val.jumpType);
                              }}
                            >
                  <render
                                key={val.i}
                                conf={val}
                                onbtnTurn={(e, jumpType) => {
                                  this.changepath(e, jumpType);
                                }}
                                onimgTurn={(e, jumpType) => {
                                  this.changepath(e, jumpType);
                                }}
                                onfunctionMenuRend={(e) => {
                                  this.functionMenuPath(e);
                                }}
                                onsearchBtn={(e) => {
                                  this.searchBtn(e);
                                }}
                              ></render>
        </div>
                    </grid-item>  
                })
               }
                  </grid-layout>:''}
             
              </van-tab>
          )
        })
           }
          </van-tabs>
  }
  function drawMobile(h) {
    return (
      <div class="pageBox">
        {this.loginCent && this.isShowLogin ? (
          <login-page onisJumpLogin={this.isJumpLogin} loginFormList={this.pageListShow.loginForm} class="reviewLogin"></login-page>
        ) : (
          ""
        )}
        {
          !this.loginCent && this.showFunMenu ? <div class="pageInfo">
            <div class="topBlock">
                        <span class="leftTurn" onClick={this.funMenuBack}></span>
                      </div>
                   
                      <div style={{display:'flex',flexWrap:'wrap'}}>
                        {this.funMenuShow.map((menuinfo,menubgid)=>{
              return (<div key={menuinfo.id} onClick={()=>{this.funMenuBtn(menuinfo.childMenus || menuinfo.path)}} class="funmenubox">
                <div class="menuItem" style={{background:`linear-gradient(180deg,${this.colorArr[(menubgid+1)%8]} 100%)`}}>
          <svg-icon 
            slot="prefix" 
            icon-class={menuinfo.icon?menuinfo.icon:'quickMenu'} 
            class="el-input__icon"
            style={{height:'32px',width:'24px',color:'white'}} 
          />
        </div>
        <div class="menuText">{menuinfo.name}</div>
                </div>)
             })}
                        </div> 
            </div> : ''
        }
        {
          !this.loginCent && this.showSearch ? <search-cent searchOptionsData={this.searchOptionsData} oncloseSearchBtn={this.closeSearchBtn}></search-cent> : ''
        }
        {!this.loginCent && !this.showFunMenu
          ? this.pageListAllCopy.map((cur, curindex) => {
              return (
                
                  <div class="pageInfo" style={{flexBasis:this.curPath === cur.name?'auto':'0px'}}>
                    {this.pageListShow.navList.length && 
                    this.pageListShow.navList[0].bottomData.filter((navtime) => {
                      return navtime.jumpPath;
                    }).length > 0 &&
                    this.pageListShow.navList[0].bottomData.filter((navtime) => {
                      return navtime.jumpPath && navtime.jumpPath === this.curPath;
                    }).length === 0 ? (
                      <div class="topBlock">
                        <span class="leftTurn" onClick={this.backPage}></span>
                        {cur.name}
                      </div>
                    ) : (
                      ""
                    )}
                    {!this.pageListShow.navList.length && curindex !== 0 ? (
                      <div class="topBlock">
                        <span class="leftTurn" onClick={this.backPage}></span>
                        {cur.name}
                      </div>
                    ) : (
                      ""
                    )}
                    {
                      cur.name==='我的' ? <user-mobile></user-mobile> : ''
                    }
                    <grid-layout
                      layout={cur.fields}
                      col-num={12}
                      row-height={30}
                      is-resizable={false}
                      is-mirrored={false}
                      vertical-compact={false}
                      
                      is-draggable={false}
                      auto-size={false}
                      margin={[0,5]}
                      use-css-transforms={false}
                      use-style-cursor={false}
                    >
                      {cur.fields.map((item) => {
                        return (
                          <grid-item
                            x={item.x}
                            y={item.y}
                            w={item.w}
                            h={item.h}
                            i={item.i}
                          
                            style={{
                              background: "white"
                            }}
                          >
                            <div
                              style={{width: '100%',background:'white',height:'100%',overflow:item.__config__.tag==='biaoqian'?'auto':'hidden'}}
                              onClick={() => {
                                this.changepath((item.jumpType==='page'?item.jumpPath:item.functionMenu), item.jumpType);
                              }}
                            >
                            {item.__config__.tag==='biaoqian'?
                            freeDraw.call(this,h,item):
                            <render
                                key={item.i}
                                conf={item}
                                onbtnTurn={(e, jumpType) => {
                                  this.changepath(e, jumpType);
                                }}
                                onimgTurn={(e, jumpType) => {
                                  this.changepath(e, jumpType);
                                }}
                                onfunctionMenuRend={(e) => {
                                  this.functionMenuPath(e);
                                }}
                                onsearchBtn={(e) => {
                                  this.searchBtn(e);
                                }}
                              ></render>
                          }
                              
                            </div>
                          </grid-item>
                        );
                      })}
                    </grid-layout>
                  </div>
                
              );
            })
          : ""}
        {!this.loginCent && !this.showFunMenu && this.pageListShow.navList.length && this.pageListShow.navList[0].bottomData.filter((navtime) => {
                      return navtime.jumpPath === this.curPath;
                    }).length > 0 ? (
          <div class="bottomNav">
            <render
              conf={this.pageListShow.navList[0]}
              tabind={this.tabind}
              oncurrentTitle={(e) => {
                this.changepath(e, 'page');
              }}
            ></render>
          </div>
        ) : (
          ""
        )}
      </div>
    );
  }
  export default {
    data() {
      return {
        curPath: "",
        pageListAllCopy: [],
        bottomInfo: [],
        trunPath: [],
        loginCent: false, //pc上面发布预览时候，要展示登录界面，别无他用
        menuId:[],
        tabind:0,
        pageListShow:{},
        showbiao:true,
        showFunMenu:false,
        funMenuShow:[],
        funmenarr:[],
        menuPathList:[],
        funtime:'',
        showSearch:false,
        searchOptionsData:[],
        colorArr:['#b9a0ff, #9281ff','#90cafa, #5795f8','#9ddd49, #7ecb45','#ffe06c, #ffb63d','#ffa0ce, #ec8283',
    '#ffab75, #ff7d67','#7bf9f1, #46d3f2','#79afff, #4a92ff']
      };
    },
    components: {
      render,
      GridLayout: VueGridLayout.GridLayout,
      GridItem: VueGridLayout.GridItem,
      loginPage,
      searchCent
    },
    props: {
      pageListAll: {
        type: Object,
        default: function () {
          return {};
        },
      },
      isShowLogin: {
        type: Boolean,
        default: false,
      },
    },
    watch:{
      loginCent(){
         this.setTabRefresh();
      }
    },
    beforeRouteUpdate(to,from,next) {
      // 如果有功能菜单，则点进去之后它的子菜单要单独显示在一个页面，若还有子菜单，则以此类推
      if(to.query.functionMenu==='functionMenu'){
        this.showFunMenu = true;
        let curtime = to.query.menutime || '';
        if(curtime<this.funtime){
          this.menuPathList.pop();
        }
        this.handlerPreMenu((to.query.menus.split(',') || []));
      }else if (to.params.curPath) {
        this.showFunMenu = false;
        this.curPath = to.params.curPath;
        this.setTabIndex(this.curPath);
        this.updatePassWordHandler();
      }
      next();
    },
    created() {
      console.log('初始',this.curPath,this.$route.params.curPath,'v',this.$route.query);
      this.pageListShow = this.pageListAll;
      // 如果是在手机上则 pageListAll 取本地数据
      if (!this.$store.state.mobile.isJump && window.localStorage.getItem("mobileDrawObj")) {
        let drawobj = JSON.parse(window.localStorage.getItem("mobileDrawObj"));
        this.pageListShow = drawobj.pageListAll;
      }
      this.pageListShow.pageList.forEach((item) => {
         Array.isArray(item.children) && this.pageListAllCopy.push(...item.children);
      });
      this.curPath = this.$route.params.curPath || this.pageListAllCopy[0].name;
      this.trunPath.push(this.pageListAllCopy[0].name); //存储第一个路由
      if (this.pageListShow.navList.length) { //如果有底部tab组件
        this.bottomInfo = this.pageListShow.navList[0].bottomData.map((info) => {
          return info.jumpPath;
        });
       this.setTabIndex(this.curPath);
      }
      let menuIdlist = window.localStorage.getItem('ownmenulists');
      this.menuId = menuIdlist?JSON.parse(menuIdlist):[];
      if(this.$route.query.functionMenu==='functionMenu'){ //功能菜单需要单独显示
        this.showFunMenu = true;
        this.getMenuListAll();
        this.handlerPreMenu((this.$route.query.menus.split(',') || []));
      }
      //如果是手机上展示，则要去获取菜单
      if(!this.$store.state.mobile.isJump){
       this.getTreeselect();
      }
    },
    mounted(){
     this.setTabRefresh();
    },
    methods: {
      // 路径跳转
      changepath(path, pathtype) {
        if (path) {
          if (pathtype === "page") {
            this.trunPath.push(path); // 推入页面路径
            if (this.$store.state.mobile.isJump) { //pc上面的预览
              this.curPath = path;
              this.setTabIndex(path);
              this.updatePassWordHandler();
            } else {  // 手机上的则跳转
              this.$router.push(`/iphonePath/${path}`);
            }
          } else if (pathtype === "function") {
           !this.$store.state.mobile.isJump && this.$router.push(path); //只有在手机上跳转至功能才生效，pc端预览不让跳转
          }
        }
      },
      // 返回
      backPage() {
        this.trunPath.pop();
        if(!this.trunPath.length){
        this.trunPath.push(this.pageListAllCopy[0].name); //始终保存第一个页面
        }
        let backPath = this.trunPath[this.trunPath.length - 1];
        if (this.$store.state.mobile.isJump) { //pc上面的预览
          this.curPath = backPath;
          this.setTabIndex(this.curPath);
        } else { // 手机上的则跳转
          this.$router.push(`/iphonePath/${backPath}`);
        }
      },
      // pc上面发布预览时候，要展示登录界面，预览的登录界面登录后隐藏登录界面
      isJumpLogin() {
        this.loginCent = false;
      },
      // 如果当前页面是存在于底部导航栏，高亮对应底部导航栏
      setTabIndex(path){
        this.tabind = this.bottomInfo.findIndex(val=>{
          return path === val;
        });
      },
      // 功能菜单模块的跳转，如果有子菜单，则根据子菜单的id显示子菜单，隐藏当前页面其他元素，依次类推
      functionMenuPath(e){
        window.localStorage.setItem('functionmenus',JSON.stringify(e));
        this.getMenuListAll();
        let str = e.map(val=>{return val.id});
        if(!this.$store.state.mobile.isJump){ //在手机上需要跳转
          this.menuPathList.push(str.toString());
          this.funtime = Date.now();
          this.$router.push(`/iphonePath?functionMenu=functionMenu&menus=${str.join(',')}&menutime=${this.funtime}`);
        }else{
          this.funMenuBtn(e);
        }
      },
      funMenuBtn(childMenus){
        if(Array.isArray(childMenus)){ //如果有子菜单，显示菜单，隐藏其他元素（手机上是跳转并且触发beforeRouteUpdate）
          let arr = childMenus.map(val=>{
               return val.id;
        });
        this.menuPathList.push(arr.toString());
        this.showFunMenu = true;
        if(!this.$store.state.mobile.isJump){ //手机上
          this.funtime = Date.now();
          this.$router.push(`/iphonePath?functionMenu=functionMenu&menus=${arr.join(',')}&menutime=${this.funtime}`);
        }else{  // pc端
          this.handlerPreMenu(arr);
        }
        }else{ //如果没有子菜单，说明到最后一层菜单了，则直接跳转
          if(!this.$store.state.mobile.isJump){
          this.$router.push(childMenus);
        }
        }
      },
      handlerPreMenu(arrids){
        console.log(arrids,'arridsbbbb');
        // 如果在手机上则根据当前用户所能看到的功能菜单，显示对应的菜单
        // pc上面暂时展示全部菜单
        let infoarr;
        if(!this.$store.state.mobile.isJump){
          infoarr = arrids.filter(val=>{
          return this.menuId.some(n=>{
            return n==val;
          });
        });
        }else{
          infoarr = arrids
        }
       let showArr = this.funmenarr.filter(val=>{
          return infoarr.some(n=>{
            return n==val.id;
          })
        });
        this.funMenuShow = showArr;
      },
     
      getMenuListAll(){
        let funarr = [];
        let list = JSON.parse(window.localStorage.getItem('functionmenus'));
        
        function handlerMenus(arr){
          for(let i=0;i<arr.length;i++){
           funarr.push(arr[i]);
           if(Array.isArray(arr[i].childMenus) && arr[i].childMenus.length){
            handlerMenus(arr[i].childMenus);
           }
          }
        }
        handlerMenus(list);
        this.funmenarr = JSON.parse(JSON.stringify(funarr));
      },
      // 获取当前用户权限下的菜单，存储其id
      getTreeselect() {
        getRouters().then((response) => {
          response.data.map((item) => {
            this.changeChildren(item);
          });
         
           setTimeout(()=>{
              // 如果页面包含功能菜单组件functionMenu，则要根据用户的权限展示不同的功能菜单
              window.localStorage.setItem('ownmenulists',JSON.stringify(this.menuId));
              this.pageListAllCopy.forEach(val=>{
                let arr = val.fields.filter(info=>{
                  return info.__config__.tag==='functionMenu'
                });
                arr.forEach(cent=>{
                  let centarr = cent.bottomData.filter(defcent=>{
                   return this.menuId.includes(defcent.id) || !defcent.id;
                  });
                   cent.bottomData = centarr;
                });
              });
            },0);
        });
      },
      //处理树结构children
      changeChildren(item) {
        this.menuId.push(item.id);
        if (Array.isArray(item.children)) {
          item.children.map((data) => {
            this.changeChildren(data);
          });
        }
      },
      //功能菜单的返回
      funMenuBack(){
       
        this.menuPathList.pop();
        if(this.menuPathList.length){
          let str = this.menuPathList[this.menuPathList.length-1];
          this.handlerPreMenu(str.split(','));
        }else{
          this.showFunMenu = false;
        }
        
      },
      searchBtn(e){
        this.searchOptionsData = e;
        this.showSearch = true;
      },
      setTabRefresh(){ //vant中标签组件在登录后和预览时候不能正确高亮当前tab页面，强制更新
        this.showbiao = false;
        setTimeout(()=>{
          this.showbiao = true;
          this.$forceUpdate();
        },0)
        
      },
      closeSearchBtn(){
        this.showSearch = false;
      },
      updatePassWordHandler(){
        let len = [];
        let curarr = this.pageListAllCopy.find(item=>{
          return item.name === this.curPath;
        }).fields;
        let curarr2 = curarr.filter(item=>{
          return item.__config__.tag === 'source-detail';
        });
        if(curarr2.length){
          curarr2.forEach(val=>{
          len.push(val.source);
          val.source = '';
        })
        setTimeout(()=>{
          curarr2.forEach((val,ind)=>{
          val.updateText = Date.now();
          val.source = len[ind];
        })
        },0)
        }
      }
    },
    render(h) {
      return drawMobile.call(this, h);
    },
  };
  </script>
  <style lang="scss" scoped>
  .pageBox {
    height: 100vh;
    width: 100vw;
    overflow: hidden;
    display:flex;
    flex-wrap: nowrap;
    flex-direction: column;
    align-items: center;
    justify-content: flex-end;
    position: relative;
    .pageInfo {
      width: 100%;
      height: 100%;
      flex:1;
      overflow-y: auto;
      overflow-x: hidden;
    }
    .funmenubox{
      display:flex;
      flex-direction: column;
      align-items: center;
      margin:10px;
      .menuItem{
        width: 50px;
    height: 50px;
    background: #1F78FE;
    border-radius: 50%;
    display:flex;
    justify-content: center;
    align-items: center;
      }
      .menuText{
        width:90px;
        overflow: hidden;
        text-overflow: ellipsis;
    white-space: nowrap;
    margin-top:5px;
    text-align: center;
      }
    }
    .topBlock {
      width: 100%;
      height: 38px;
      font-size:14px;
      background: white;
      line-height: 38px;
      text-align: center;
      position: relative;
      border-bottom: 0.5px solid #f4f4f4;
      .leftTurn {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        width: 28px;
        height: 28px;
        left: 10px;
        background: url("../../../../assets/images/leftjump.png");
        background-repeat: no-repeat;
        background-size: 100% 100%;
        cursor: pointer;
      }
    }
    .bottomNav {
      width: 100%;
      flex:none;
    }
    .reviewLogin{
      width:387px;
      border-bottom-right-radius: 30px;
      border-bottom-left-radius: 30px;
      overflow: hidden;
    }
  }
  @media only screen and (min-width: 768px) {
    .pageBox {
      width: 448px;
      height: 880px;
      background: url("../../../../assets/images/iphone.png");
      background-repeat: no-repeat;
      background-size: 100% 100%;
      padding-top:60px;
    padding-bottom:46px;
      .pageInfo {
        width: 375px;
        height: 100%;
      }
      .bottomNav {
        width: 375px;
        overflow: hidden;
        border-radius: 22px;
      }
    }
  }
  ::-webkit-scrollbar{
    width:0px;
  }
  </style>
  <style>
    .pageBox  .van-tabs__line{
    background:#1890FF;
  }
  .pageBox  .van-tabs__nav--card .van-tab.van-tab--active{
    background:#1890FF;
  }
  .pageBox .van-tab--card{
    color:#646566;
  }
  .pageBox .van-tabs__nav--card .van-tab{
   
    border-right:1px solid #1890FF;
  }
  .pageBox .van-tabs__nav--card{
    border:1px solid #1890FF;
  }
  .van-tabs__nav--card .van-tab{
    color:#646566;
  }
  </style>